<?php
namespace Modules\Core\Http\Controllers\Client\V1;

use Illuminate\Http\Request;
use Illuminate\Routing\Controller;

use Illuminate\Support\Facades\DB;
use Modules\Activity\Entities\ActivityOrder;
use Modules\Activity\Entities\Choushang\Activity as ChoushangActivity;
use Modules\Activity\Entities\Leitai\Activity as LeitaiActivity;
use Modules\Agent\Entities\InviteRecord2;
use Modules\Order\Entities\BaseOrder as Order;
use Validator;
use ThrowException;
use Miniapp;
use Setting;
use Wechat;

class WechatController extends Controller
{
    // 
    public function miniappSubscribeIdIndex(Request $req)
    {
        $rule = [
        ];
        Validator::make($req->all(), $rule)->fails() && ThrowException::BadRequest(); 


        // 模板id
        $cacheKey = 'miniapp_subscribe_template_ids';
        $ids= @Setting::get($cacheKey) ?: [];

        $fresh = false;

        foreach (config('subscribeMessage.miniapp') as $type => $item) {

            $templateId = @$ids[$type];

            if (!$templateId) {
                $info = config('subscribeMessage.miniapp.' . $type);

                $tid = $info['id']; 
                $kidList = $info['words'];      
                $sceneDesc = $info['desc'];
                $info = Miniapp::get('default')->subscribe_message->addTemplate($tid, $kidList, $sceneDesc);
                $templateId = @$info['priTmplId'];

                if (!$templateId) {
                    \Log::error('订阅消息模板添加失败' . $type);
                    \Log::error($info);

                    return ThrowException::Conflict('订阅消息模板添加失败~');
                }

                $ids[$type] = $templateId;
                $fresh = true;
            }
        }

        if ($fresh) {
            Setting::set($cacheKey, $ids);
        }

        return [
            'ids' => $ids
        ];
    }

    // 获取小程序码
    public function miniappCode(Request $req)
    {
        $rule = [
            'path' => ['required']
        ];
        Validator::make($req->all(), $rule)->fails() && ThrowException::BadRequest(); 

        $path = $req->path;

        if ($req->isMethod('post')) {
            // 小程序码
            $qrcode = @Miniapp::get('default')->getMiniappCode($path);

            return [
                'qrcode' => $qrcode
            ];
        }
        else {
             // 小程序码
            $qrcode = @Miniapp::get('default')->getMiniappCode($path, false);

            return $qrcode;
        }
    }

    // 微信见面获取js初始化数据
    public function jssdkConfig(Request $req)
    {
        $rule = [
            'url' => ['required']
        ];
        Validator::make($req->all(), $rule)->fails() && ThrowException::BadRequest(); 

        $url = $req->url;

        $apis = [
            'chooseWXPay',
            'updateAppMessageShareData',
            'updateTimelineShareData',
            'scanQRCode'
        ];

        // $url = 'https://kmhd.hquesoft.com';

        $config = Wechat::get()->jssdkConfig($url, $apis);

        return [
            'config' => $config
        ];
    }

    public function getDmwInfo(Request $req)
    {
        if ( !isset($req->node_id) || !$req->node_id ){
            echo json_encode(array('code'=>10001, 'status_code'=>401, 'message'=>'参数异常！'));
            die;
        }

        $time = date('Y-m-d H:i:s');
        $res = DB::select("select * from dmw_reward where node_id = {$req->node_id} and status = 1 and max_time > '$time' ");

        if ( count($res) == 0 ){
            echo json_encode(array('code'=>10001, 'status_code'=>201, 'message'=>'查询无结果'));
            die;
        }

        $res = array_map('get_object_vars', $res) ;
        $row = $res[0];
        $user_info = DB::select("select * from users where id = {$row['user_id']} ");
        $user_info = array_map('get_object_vars', $user_info) ;
        $user_info = $user_info[0];

        $fudai_info = DB::select("select * from fudai_activity where id = {$req->node_id} and is_dmw_enabled = 1 ");
        if ( !(count($fudai_info) > 0) ){
            echo json_encode(array('code'=>10001, 'status_code'=>201, 'message'=>'魔王已关闭'));
            die;
        }
        $fudai_info = array_map('get_object_vars', $fudai_info) ;
        $fudai_info = $fudai_info[0];

        $row['user_name'] = $user_info['name'];
        $row['head_img'] = $user_info['headimg'];
        $row['dmw_type'] = $fudai_info['dmw_type'];
        if ( $row['dmw_type'] == 2 ){
            $row['issued_reward'] = $row['issued_reward'] / 100;
        }

        $start_date= $row['create_time'];//开始时间
        $end_date= $time;//结束时间

        $minute=round((strtotime($end_date)-strtotime($start_date))/60);
        $row['minute'] = $minute;

        echo json_encode(array('code'=>10001, 'status_code'=>200, 'message'=>$row));
        die;
    }

    public function test()
    {
        $orders = Order::paid()->where([
            'share_status' => 0,
            ['sharer', '>', 0]
        ])->get();

        foreach ($orders as $order) {
            InviteRecord2::createWith($order);
        }
        echo '<pre>';
        print_r($orders);
        echo '</pre>';
        echo '<hr>';
        die;
        
        ini_set("memory_limit",'-1');
        $uuid = '63ff6603c6c48';

        
        $item_r = DB::table('leitai_activity')->where('uuid', $uuid)->first();
        $uuid_arr = array();
        $act_init = object_to_array($item_r);
        $act_init['stock'] += $act_init['sales'];
        $act_init['sales'] = 0;
        $act_arr = array();
        $time = date('Y-m-d H:i:s');
        for ( $i=0; $i<10000; $i++ ){
            $a_uuid = uniqid();
            array_push($uuid_arr, $a_uuid);
            $act_arr[$i] = $act_init;
            $act_arr[$i]['uuid'] = $a_uuid;
            $act_arr[$i]['created_at'] = $time;
            $act_arr[$i]['updated_at'] = $time;
            unset($act_arr[$i]['id']);
        }
        DB::table('leitai_activity')->insert($act_arr);

        $id_obj = DB::table('leitai_activity')->whereIn('uuid', $uuid_arr)->get()->toArray();
        $id_arr = array_column($id_obj, 'id');

        $sku_r = DB::table('leitai_skus')->where('activity_id', $item_r->id)->get()->toArray();
        $sku_arr = array();
        $index_sku = 0;
        foreach ( $id_arr as $k => $v ){
            foreach ( $sku_r as $sk => $sv ){
                $a_uuid = uniqid();
                $sku_arr[$index_sku] = object_to_array($sv);
                $sku_arr[$index_sku]['activity_id'] = $v;
                $sku_arr[$index_sku]['uuid'] = $a_uuid;
                $sku_arr[$index_sku]['created_at'] = $time;
                $sku_arr[$index_sku]['updated_at'] = $time;
                unset($sku_arr[$index_sku]['id']);
                $index_sku++;
            }
        }
        DB::table('leitai_skus')->insert($sku_arr);
        unset($sku_arr);
        unset($sku_r);

        $sku_r = DB::table('leitai_last_skus')->where('activity_id', $item_r->id)->get()->toArray();
        $sku_arr = array();
        $index_sku = 0;
        foreach ( $id_arr as $k => $v ){
            foreach ( $sku_r as $sk => $sv ){
                $a_uuid = uniqid();
                $sku_arr[$index_sku] = object_to_array($sv);
                $sku_arr[$index_sku]['activity_id'] = $v;
                $sku_arr[$index_sku]['uuid'] = $a_uuid;
                $sku_arr[$index_sku]['created_at'] = $time;
                $sku_arr[$index_sku]['updated_at'] = $time;
                unset($sku_arr[$index_sku]['id']);
                $index_sku++;
            }
        }

        DB::table('leitai_last_skus')->insert($sku_arr);


        die('okk');
        $last_skus_init = $item->last_skus->toArray();

        foreach ( $sku_init as $k => $v ){
            $sku_init[$k]['stock'] = $v['stock'] + $v['sales'];
            $sku_init[$k]['sales'] = 0;
        }

        foreach ( $last_skus_init as $k => $v ){
            $last_skus_init[$k]['stock'] = $v['stock'] + $v['sales'];
            $last_skus_init[$k]['sales'] = 0;
        }

        echo '<pre>';
        print_r($item->toArray());
        echo '</pre>';
        echo '<hr>';
        die;

        if ( $req->nums > 0 ){
            $newItem = Activity::create($info);
            $skuArray = [];

            $stock = array();
            foreach ($item->skus as $sku) {
                if ( !isset($stock[$sku->title]) ){
                    $stock[$sku->title] = $sku->stock + $sku->sales;
                }

                $skuInfo = $sku->getInfo([
                    'activity_id',
                    'sku_type',
                    'assets',
                    'product_id',
                    'title',
                    'number',
                    'thumb',
                    'money_price',
                    'score_price',
                    'stock',
                    'odds',
                    'level',
                    'list_weight',
                    'status',
                    'is_resaleable',
                    'display_money_price',
                    'discount_score_price',
                    'detail_images',
                    'return_sale_ratio',
                    'use_lucky_score'
                ]);
                $skuInfo['stock'] = $stock[$sku->title];
                $skuInfo['uuid'] = uniqid();

                array_unshift($skuArray, $skuInfo);
            }

            $lastSkuArray = [];
            $last_stock = array();
            foreach ($item->last_skus as $sku) {
                if ( !isset($last_stock[$sku->title]) ){
                    $last_stock[$sku->title] = $sku->stock + $sku->sales;
                }
                $lastSkuInfo = $sku->getInfo([
                    'activity_id',
                    'sku_type',
                    'assets',
                    'product_id',
                    'title',
                    'number',
                    'thumb',
                    'money_price',
                    'score_price',
                    'stock',
                    'odds',
                    'level',
                    'list_weight',
                    'status',
                    'is_resaleable',
                    'display_money_price',
                    'discount_score_price',
                    'detail_images',
                    'return_sale_ratio',
                    'last_prize_type',
                    'show_to',
                    'more_value1',
                    'more_value2',
                    'kong_value',
                    'use_lucky_score'
                ]);
                $lastSkuInfo['stock'] = $last_stock[$sku->title];
                $lastSkuInfo['uuid'] = uniqid();

                array_unshift($lastSkuArray, $lastSkuInfo);
            }


            for ( $i=0; $i<$req->nums; $i++ ){
                $newItem = Activity::create($info);
                $skuArray = [];

                $stock = array();
                foreach ($item->skus as $sku) {
                    if ( !isset($stock[$sku->title]) ){
                        $stock[$sku->title] = $sku->stock + $sku->sales;
                    }

                    $skuInfo = $sku->getInfo([
                        'activity_id',
                        'sku_type',
                        'assets',
                        'product_id',
                        'title',
                        'number',
                        'thumb',
                        'money_price',
                        'score_price',
                        'stock',
                        'odds',
                        'level',
                        'list_weight',
                        'status',
                        'is_resaleable',
                        'display_money_price',
                        'discount_score_price',
                        'detail_images',
                        'return_sale_ratio',
                        'use_lucky_score'
                    ]);
                    $skuInfo['stock'] = $stock[$sku->title];
                    $skuInfo['uuid'] = uniqid();

                    array_unshift($skuArray, $skuInfo);
                }

                $lastSkuArray = [];
                $last_stock = array();
                foreach ($item->last_skus as $sku) {
                    if ( !isset($last_stock[$sku->title]) ){
                        $last_stock[$sku->title] = $sku->stock + $sku->sales;
                    }
                    $lastSkuInfo = $sku->getInfo([
                        'activity_id',
                        'sku_type',
                        'assets',
                        'product_id',
                        'title',
                        'number',
                        'thumb',
                        'money_price',
                        'score_price',
                        'stock',
                        'odds',
                        'level',
                        'list_weight',
                        'status',
                        'is_resaleable',
                        'display_money_price',
                        'discount_score_price',
                        'detail_images',
                        'return_sale_ratio',
                        'last_prize_type',
                        'show_to',
                        'more_value1',
                        'more_value2',
                        'kong_value',
                        'use_lucky_score'
                    ]);
                    $lastSkuInfo['stock'] = $last_stock[$sku->title];
                    $lastSkuInfo['uuid'] = uniqid();

                    array_unshift($lastSkuArray, $lastSkuInfo);
                }

                $newItem->skus()->createMany($skuArray);
                $newItem->last_skus()->createMany($lastSkuArray);
            }
        }

        return [];

        die;


        $a = '4%E4%BA%BAPK%E5%BF%8D%E8%80%85%E7%A5%9E%E9%BE%9F%26%E8%89%BE%E5%B0%94%E7%B3%BB%E5%88%97%E6%B5%8B%E8%AF%95%E4%B8%93%E5%8C%BA';
        $a = '4%E4%BA%BAPK%E5%BF%8D%E8%80%85%E7%A5%9E%E9%BE%9F%26%E8%89%BE%E5%B0%94%E7%B3%BB%E5%88%97%E6%B5%8B%E8%AF%95%E4%B8%93%E5%8C%BA';
        $b = iconv('UTF-8','gb2312',$a);

        $a1 = '4人PK忍者神龟&艾尔系列测试专区';
        $b = urldecode($a);
        echo '<pre>';
        print_r($b);
        echo '</pre>';
        echo '<hr>';
        die;
        die;
        $activity_id = 171;
        $activity = LeitaiActivity::getEntity([
            'id' => $activity_id
        ]);

        $sku_arr = DB::table('leitai_skus')->where(array('activity_id'=>$activity_id))->get();

        $oper_chk_arr = array(
            'node_id' => $activity_id,
            'node_type' => 'leitai'
        );
        $order_list = DB::table('orders')->where($oper_chk_arr)->whereNotNull('pay_type')->whereIn('pay_status', array(2, 3))->select(['id', 'user_id'])->get()->toArray();

        $order_cnt = count($order_list);

        // 空车人员
        $user_arr = array_column($order_list, 'id', 'user_id');

        $prize_arr = array();
        foreach ( $sku_arr as $sku_item ){
            for ( $i=0;$i<$sku_item->stock;$i++ ){
                // 中奖 下标
                $prize_index = rand(0, $order_cnt-1);
                $prize_arr[$order_list[$prize_index]->id]['sku_id'][] = $sku_item->id;
                unset($user_arr[$order_list[$prize_index]->user_id]);

                // 分配普通奖
                $this->setLeitaiPrize($activity, $order_list[$prize_index]->id, $sku_item, $order_list[$prize_index]->user_id, 'leitai_skus');
            }
        }

        // 空车人员++
        if ( count($user_arr) > 0 ){
            foreach ($user_arr as $user_arr_k => $user_arr_v){
                DB::update('update users set leitai_kongche = leitai_kongche +1  where id = ? ',[$user_arr_k]);
            }
        }

        $prize_info = array();
        foreach ( $prize_arr as $order_id => $p_arr ){
            $prize_cnt = count($p_arr['sku_id']);
            $prize_info[$prize_cnt][] = $order_id;
        }

        $sku_last_arr = DB::table('leitai_last_skus')->where(array('activity_id'=>$activity_id))->get()->toArray();
        if ( count($sku_last_arr) > 0 ){
            foreach ( $sku_last_arr as $k => $v ){
                if ( $v->last_prize_type == 3 ){
                    // 保底奖
                    foreach ( $order_list as $baodi_k => $baodi_v ){
                        $this->setLeitaiPrize($activity, $baodi_v->id, $v, $baodi_v->user_id, 'leitai_last_skus');
                    }
                }
                if ( $v->last_prize_type == 1 ){
                    // S奖
                    for ( $i=0;$i<$v->stock;$i++ ){
                        // 中奖 下标
                        $prize_index = rand(0, $order_cnt-1);
                        $this->setLeitaiPrize($activity, $order_list[$prize_index]->id, $v, $order_list[$prize_index]->user_id, 'leitai_last_skus');
                    }
                }

                if ( $v->last_prize_type == 4 && $v->more_value > 0 ){
                    // 一串多
                    $order_user_ = array_column($order_list, 'user_id', 'id');
                    foreach ( $prize_info as $prize_info_k => $prize_info_v ){
                        if ( $prize_info_k == $v->more_value ){
                            // 中奖订单
                            foreach ( $prize_info_v as $prize_info_v_arr ){
                                $this->setLeitaiPrize($activity, $prize_info_v_arr, $v, $order_user_[$prize_info_v_arr], 'leitai_last_skus');
                            }
                        }
                    }
                }

                if ( $v->last_prize_type == 2 && $v->more_value > 0 ){
                    // 空空奖
                    $order_user_arr = array_column($order_list, 'user_id');
                    $kongche_chk = DB::table('users')->whereIn('id', $order_user_arr)->where('leitai_kongche', '=', $v->more_value)->first(
                        \DB::raw('group_concat(id) as user_id')
                    );
                    if ( $kongche_chk->user_id ){
                        $user_kc_prize_arr = explode(',', $kongche_chk->user_id);
                        $order_user_ = array_column($order_list, 'id', 'user_id');
                        foreach ( $user_kc_prize_arr as $user_kc_prize_arr_k => $user_kc_prize_arr_v ){
                            $this->setLeitaiPrize($activity, $order_user_[$user_kc_prize_arr_v], $v, $user_kc_prize_arr_v, 'leitai_last_skus');
                        }

                    }
                }
            }
        }

        return 1111;
    }

    public function setLeitaiPrize($activity, $order_id, $sku_item, $user_id, $stock_db = 'leitai_skus', $set_kong_=1)
    {
        $stock = DB::table($stock_db)->where('id', $sku_item->id)->where('stock', '>', 0)->first();
        if ( !$stock ){
            return false;
        }
        DB::beginTransaction();
        $package = DB::table('package_assets')->where(array('activity_id'=>$activity->id, 'pay_order_id'=>$order_id))->first();
        if ( !$package ){
            $arr = array();
            $arr['uuid'] = uniqid();
            $arr['title'] = $activity->title;
            $arr['user_id'] = $user_id;
            $arr['node_money_price'] = $activity->money_price;
            $arr['node_score_price'] = $activity->score_price;
            $arr['activity_id'] = $activity->id;
            $arr['node_id'] = $activity->id;
            $arr['activity_type'] = '擂台';
            $arr['node_type'] = '擂台';
            $arr['activity_uuid'] = $activity->uuid;
            $arr['node_uuid'] = $activity->uuid;
            $arr['status'] = 1;
            $arr['sku_total'] = 1;
            $arr['pay_order_id'] = $order_id;
            $arr['created_at'] = date('Y-m-d H:i:s');
            $arr['updated_at'] = date('Y-m-d H:i:s');
            $package_id = DB::table('package_assets')->insertGetId($arr);
        }else{
            DB::update('update package_assets set sku_total = sku_total + 1 where id = ? ',[$package->id]);
            $package_id = $package->id;
        }

        $arr = array();
        $arr['uuid'] = uniqid();
        $arr['title'] = $sku_item->title;
        $arr['package_asset_id'] = $package_id;
        $arr['user_id'] = $user_id;
        $arr['thumb'] = $sku_item->thumb;
        $arr['money_price'] = $sku_item->money_price;
        $arr['score_price'] = $sku_item->score_price;
        $arr['sku_type'] = $sku_item->sku_type;
        $arr['pay_order_id'] = $order_id;
        $arr['total'] = 1;
        $arr['status'] = 1;
        $arr['created_at'] = date('Y-m-d H:i:s');
        $arr['updated_at'] = date('Y-m-d H:i:s');
        $arr['node_title'] = $activity->title;
        $arr['node_money_price'] = $activity->money_price;
        $arr['node_score_price'] = $activity->score_price;
        $arr['activity_id'] = $activity->id;
        $arr['node_id'] = $activity->id;
        $arr['activity_type'] = '擂台';
        $arr['node_type'] = '擂台';
        $arr['activity_uuid'] = $activity->uuid;
        $arr['node_uuid'] = $activity->uuid;
        $arr['sku_id'] = $sku_item->id;

        $package_sku_id = DB::table('package_skus')->insertGetId($arr);

        $sql = "update $stock_db set stock = stock - 1, sales = sales + 1 where id = ".$sku_item->id;
        DB::update($sql);

        if ( $set_kong_ == 1 ){
            // 空车为0
            DB::update('update users set leitai_kongche = 0 where id = ? ',[$user_id]);
        }

        DB::commit();
        return $package_sku_id;
    }

    public function playType4CreateOrder($user_id, $activity_id)
    {
        $orders_arr['uuid'] = uniqid();
        $orders_arr['user_id'] = $user_id;
        $orders_arr['number'] = 'A' . date('mdHis') . $user_id . rand(100, 999);
        $code = rand(1000, 9999) . strVal(time()) . $user_id . '0' . rand(100000, 999999);
        $code = substr($code, -16);
        $orders_arr['code'] = $code;
        $orders_arr['pay_type'] = '';
        $orders_arr['product_total'] = 1;
        $orders_arr['sku_total'] = 1;
        $orders_arr['pay_number'] = 'A' . date('mdHis') . $user_id . rand(100, 999);
        $orders_arr['confirmed_at'] = date('Y-m-d H:i:s');
        $orders_arr['money_paid_at'] = date('Y-m-d H:i:s');
        $orders_arr['completed_at'] = date('Y-m-d H:i:s');
        $orders_arr['auto_closed_at'] = date('Y-m-d H:i:s');
        $orders_arr['auto_completed_at'] = date('Y-m-d H:i:s');
        $orders_arr['created_at'] = date('Y-m-d H:i:s');
        $orders_arr['updated_at'] = date('Y-m-d H:i:s');

        $new_orders_id = DB::table('orders')->insertGetId($orders_arr);

        $order_skus_his =  DB::table('order_skus')->where(array('order_id'=>$order_old_id))->first();
        $order_skus_his = object_to_array($order_skus_his);
        unset($order_skus_his['id']);
        $order_skus_his['uuid'] = uniqid();
        $order_skus_his['order_id'] = $new_orders_id;
        $order_skus_his['total'] = 1;
        $order_skus_his['created_at'] = date('Y-m-d H:i:s');
        $order_skus_his['updated_at'] = date('Y-m-d H:i:s');
        $new_orders_sku_id = DB::table('order_skus')->insertGetId($order_skus_his);


        $package_assets = DB::table('package_assets')->where(array('id'=>$order_his['package_asset_id']))->first();
        $package_assets = object_to_array($package_assets);

        unset($package_assets['id']);
        $package_assets['uuid'] = uniqid();
        $package_assets['title'] .= '-底奖赠送';
        $package_assets['sku_total'] = 1;
        $package_assets['pay_order_id'] = $new_orders_id;
        $package_assets['created_at'] = date('Y-m-d H:i:s');
        $package_assets['updated_at'] = date('Y-m-d H:i:s');
        $package_assets_new_id = DB::table('package_assets')->insertGetId($package_assets);


        unset($order_his['id']);
        $order_his['uuid'] = uniqid();
        $order_his['title'] = $fudaiSku['title'];
        $order_his['thumb'] = $fudaiSku['thumb'];
        $order_his['money_price'] = $fudaiSku['money_price'];
        $order_his['score_price'] = $fudaiSku['score_price'];
        $order_his['total'] = 1;
        $order_his['package_asset_id'] = $package_assets_new_id;
        $new_order_id = DB::table('package_skus')->insertGetId($order_his);
    }

}
